﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Tools;
using System.Diagnostics;
using System.Collections.Concurrent;

namespace ShowScreen
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            _ActiveScandatas1 = _ActiveScandatas2 = null;
            _ActiveScandata3 = null;
            _BE = new IDbeTool();
            _CND = new CGetNetData();
            _NetDataMode = false;
            _Filelist = null;
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            if (File.Exists("global.json"))
            {
                try
                {
                    string _filename = "global.json";
                    globalsave gs = Newtonsoft.Json.JsonConvert.DeserializeObject<globalsave>(File.ReadAllText(_filename));
                    global.SetValue(gs);
                    if (gs.ProgramerCode == "ljh_beer@163.com.copyright")
                    {
                        global.UserMode = false;
                    }
                }
                catch(Exception ee)
                {
                    MessageBox.Show("配置错误，即将退出 " + ee.Message);
                    this.Close();
                }
            }
            else
            {
                SaveGlobal();
            }
            if (global.LocalPath != null && global.LocalPath.Trim()!="" && !Directory.Exists(global.LocalPath))
                Directory.CreateDirectory(global.LocalPath);
            if( (global.tag & 256) == 0)
            if(!InitLocalMode( ))
            {
                MessageBox.Show("配置错误，即将退出");
                this.Close();
            }

        }
        private Boolean InitLocalMode()
        {
            try
            {
                NetToLocal NTL = new NetToLocal(global.NetPath, global.User, global.Pwd, global.LocalPath,global.PublicShare);
                if (!NTL.AsycDir())
                {
                    return false;
                }
                DirectoryInfo di = new DirectoryInfo(global.LocalPath);
                ScanDatas _ScanDatas = new ScanDatas(global.LocalPath);
                List<ScanDatas> list = _ScanDatas.GetListScanDatas();

                if (global.PublicShare != null)
                {
                    DirectoryInfo dip = new DirectoryInfo(global.PublicShare.LocalPath);
                    ScanDatas scandatas = new ScanDatas(global.PublicShare.LocalPath);
                    List<ScanDatas> list1 = scandatas.GetListScanDatas();
                    if(list1.Count>0)
                    list.AddRange(list1.ToArray());
                }
                if (global.PublicLink != null)
                {
                    ScanDatas publicresoure = new ScanDatas(global.PublicLink,"公共资源");
                        //;new ScanDatas("","公共资源");
                    list.Add(publicresoure);
                }
                if (list.Count > 0)
                {
                    comboBox1.Items.AddRange(list.ToArray());
                    InitCombox(1);
                    return true;
                }
            }
            catch
            {
            }
            return false;
        }
      //for jsonconfig
        private void SaveGlobal()
        {
            globalsave gs = new globalsave();
            gs.Debug = global.Debug;
            gs.tag = global.tag;
            gs.msg = global.msg;
            gs.NetPath = global.NetPath;
            gs.User = global.User;
            gs.Pwd = global.Pwd;
            gs.LocalPath = global.LocalPath;
            gs.PublicShare = global.PublicShare;
            gs.PublicLink = global.PublicLink;
            string str = Tools.JsonFormatTool.ConvertJsonString(Newtonsoft.Json.JsonConvert.SerializeObject(gs));
            File.WriteAllText("global.json", str);
        }
        private void buttonClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == -1) return;          
            {
                ScanDatas sds = (ScanDatas)(comboBox1.SelectedItem);
                if (_ActiveScandatas1 != sds)
                {
                    _ActiveScandatas1 = sds;
                    comboBox2.Items.Clear();                    
                    _PublicLinkMode = false;
                    if (sds.ToString() == "公共资源") 
                    {

                        _PublicLinkMode = true;
                        //List<ScanDatas> list = new List<ScanDatas>();
                        //foreach (string s in global.PublicLink.list.Keys)
                        //{
                        //    list.Add(new ScanDatas("", s));
                        //}
                        //if (list.Count > 0)
                        //    comboBox2.Items.AddRange(list.ToArray());
                        //InitCombox(2);
                    }
                   

                    {
                        List<ScanDatas> list = _ActiveScandatas1.GetListScanDatas();
                        if (list.Count > 0)
                            comboBox2.Items.AddRange(list.ToArray());
                        InitCombox(2);
                    }
                    pictureBox1.Visible = !_PublicLinkMode;
                    webBrowser1.Visible = _PublicLinkMode;
                    buttonViewDowMove.Visible = _PublicLinkMode;

                }
            }
        }
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.SelectedIndex == -1) return;
            {
                ScanDatas sds = (ScanDatas)(comboBox2.SelectedItem);
                if (_ActiveScandatas2 != sds)
                {
                    ChangeHeightRate(0, 0);
                    _ActiveScandatas2 = sds;
                    comboBox3.Items.Clear();                  
                    {
                        List<ScanData> list = _ActiveScandatas2.Scandatas;
                        if (_PublicLinkMode)
                        {
                            list = _ActiveScandatas2.GetListNetScanData();
                        }
                        comboBox3.Items.AddRange(list.ToArray());
                        InitCombox(3);
                    }
                }
            }
        }
        private void InitLinK(string NetPath)
        {
            _BE.B = _BE.E = 0;
            _BE.MoveToTop();
            NetToLocal NTL = new NetToLocal(global.NetPath, global.User, global.Pwd, global.LocalPath, global.PublicShare);
            
            webBrowser1.DocumentText = NTL.GetNetResource(NetPath);           
        }

        private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox3.SelectedIndex == -1) return;
            ScanData sd = (ScanData)(comboBox3.SelectedItem);
            if (sd.ExamName.EndsWith("NR"))
            {
                this.Hide();
                FormResult f = new FormResult(sd);
                f.ShowDialog();
                this.Show();
                return;
            }

            if (_ActiveScandata3 != sd)
            {
                _ActiveScandata3 = sd;
                if (_PublicLinkMode)
                {
                    string NetPath = sd.Fullpath;
                    InitLinK(NetPath);

                }
                else
                {
                    InitImage();
                    ShowItem();
                }
            }

        }

        private void InitCombox(int index)
        {
            if (index == 1)
            {
                comboBox2.Enabled = comboBox3.Enabled = false; 
                // clear others
            }
            else if (index == 2)
            {
                if (comboBox2.Items.Count > 0)
                {
                    comboBox2.Enabled = true;
                    comboBox2.Text = "";
                }
                else
                {
                    comboBox2.Enabled = false;
                    MessageBox.Show("你选择的栏目中没有可显示内容");
                }
                comboBox3.Enabled = false;
            }
            else if (index == 3)
            {
                if (comboBox3.Items.Count > 0)
                {
                    comboBox3.Enabled = true;
                    comboBox3.Text = "";
                }
                else
                {
                    comboBox3.Enabled = false;
                    MessageBox.Show("你选择的栏目中没有可显示内容");
                }
            }
        }

        private void InitImage()
        {
            _BE.B = 0;
            if (_NetDataMode)
                _BE.E = _ActiveCImgList.ImgList.Count;
            else
                _BE.E = _ActiveScandata3.ImgList.Count;
            _BE.MoveToTop();
        }
        private void buttonPre_Click(object sender, EventArgs e)
        {
            PreviousShow();
        }
        private void buttonNext_Click(object sender, EventArgs e)
        {
            NextShow();
        }
        private void NextShow()
        {
            _BE.MoveNext();
            if (_BE.HasNext)
            {
                ShowItem();
            }
            else
            {
                _BE.MovePrevious();
                textBoxMsg.Text = (_BE.ActiveIndex+1) + "/" + _BE.E  +   " 已经是最后一组,没有可以显示的图片了";
            }           
        }
        private void PreviousShow()
        {
            _BE.MovePrevious();
            if (_BE.HasNext)
            {
                ShowItem();
            }
            else
            {
                _BE.MoveNext();
                textBoxMsg.Text = (_BE.ActiveIndex+1) + "/" + _BE.E  +  "  已经是第一组,没有可以显示的图片了";
            }           
        }
        private void ShowItem()
        {
            try
            {
                string imgfilename = _ActiveScandata3.ImgList[_BE.ActiveIndex];
                pictureBox1.Image = Bitmap.FromFile(imgfilename);
                textBoxMsg.Text = (_BE.ActiveIndex + 1) + "/" + _BE.E;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
                
        private IDbeTool _BE;
        private CGetNetData _CND;
        private FileList _Filelist;
        private bool _NetDataMode;
        private CImgList _ActiveCImgList;

        public ScanDatas _ActiveScandatas1 { get; set; }
        public ScanDatas _ActiveScandatas2 { get; set; }
        public  ScanData _ActiveScandata3{ get; set; }

        public bool _PublicLinkMode { get; set; }

        private void buttonViewDowMove_Click(object sender, EventArgs e)
        {
            ChangeHeightRate( 1.2, 0);
        }

        private void ChangeHeightRate(double f, int index)
        {
            int H = TLP.Height;
            int Height1 =(int) TLP.RowStyles[index].Height;
            if (Height1 < 5)
                Height1 = H * 2 / 10;
            double dgvrate =  Height1  * 1.0 /H;
            double nrate = dgvrate * f;
            nrate = nrate > 0.95 ? 0.95 : nrate;
            nrate = nrate < 0.05 ? 0.05 : nrate;
            int NW = (int)(H * nrate);
            if (f < 0.01)
                NW = 1;
            TLP.RowStyles[index] =
               new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, NW);

        }

        private void buttonMinize_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
        }
    }

    public class ScanDatas
    {
        private List<ScanData> _scandatas;
        private string path;
        private string DirName;     
        public ScanDatas(string path ,string  ShowDirName = "" )
        {
            this.path = path;
            DirectoryInfo di = new DirectoryInfo(path);
            DirName = di.Name;
            if (ShowDirName.Trim() != "")
                DirName = ShowDirName;
            _scandatas = new List<ScanData>();
            foreach (string dirname in Tools.FileTools.SubDirNameListFromDir(path))
            {
                ScanData sd = new ScanData(dirname, path);
                if(sd.ImgList.Count>0)
                    Scandatas.Add(sd);
            }
        }

        public List<ScanDatas> GetListScanDatas()
        {
            List<ScanDatas> ret = new List<ScanDatas>();
            if(path!="")
            foreach (string dirname in Tools.FileTools.SubDirNameListFromDir(path))
            {
                ret.Add( new ScanDatas(path + "\\"+dirname));
            }
            return ret;
        }
        public List<ScanData> GetListNetScanData()
        {
            List<ScanData> ret = new List<ScanData>();
            if (path != "")
                foreach (string dirname in Tools.FileTools.SubDirNameListFromDir(path))
                {
                    ret.Add(new ScanData(dirname,path));
                }
            return ret;
        }
        public List<ScanData> Scandatas { get { return _scandatas; } }
        public override string ToString()
        {
            return DirName;
        }

    }
    public class ScanData
    {
        private string _dirname;
        private string _path;
        private string _examname;
        public ScanData(string dirname, string path)
        {
            this._dirname = dirname;
            this._path = path;

            _examname = dirname;
            if (dirname.Contains("."))
            {
                _examname = dirname.Substring(0, dirname.LastIndexOf("."));
            }
            if (Directory.Exists(Fullpath))
            {
                //List<string> examlist = Tools.FileTools.NameListFromDir(Fullpath, ".exam");
                //if (examlist.Count > 0)
                //{
                //    _examname = examlist[0].Substring(Fullpath.Length + 1);
                //    _examname = _examname.Substring(0, _examname.Length - 5);
                //}
            }
        }
        public override string ToString()
        {
            if (File.Exists(Fullpath + "\\已生成阅卷数据.txt"))
                return _examname + " 已生成阅卷数据";
            return _examname;
        }
        public string Fullpath { get { return _path + "\\" + _dirname; } }
        public string Imgpath { get { return _path + "\\" + _dirname ; } }
        public string DataFullName { get { return Fullpath + "\\data.txt"; } }
        public string ExamName { get { return _examname; } }
       
        public List<string> ImgList { get { return Tools.FileTools.NameListFromDir(Imgpath, ".jpg|.png|.tif||"); } }
    }

    public class ShareLocalNet
    {
        protected readonly ConcurrentStack<string> _dirStack = new ConcurrentStack<string>();
        protected readonly Dictionary<string, DateTime> _dcLastWriteTime = new Dictionary<string, DateTime>();

        public string _NetPath;
        public string _User;
        public string _Pwd;
        public string _LocalPth;
        public ShareLocalNet(string netpath, string user, string pwd, string locpath)
        {
            this._NetPath = netpath;
            this._User = user;
            this._Pwd = pwd;
            this._LocalPth = locpath;
        }
        public bool TestConnet()
        {
            try
            {
                if (_User == "" && _Pwd == "")
                    return connectState(_NetPath);
                return connectState(_NetPath, _User, _Pwd);
            }
            catch
            {
                return false;
            }
        }
        public void AsyncDir2(string srcDir, string destDir)
        {
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }
            DirectoryInfo srcdi = new DirectoryInfo(srcDir);
            Dictionary<string, FileInfo> srcdic = CreateDic(srcdi);
            DirectoryInfo dstdi = new DirectoryInfo(destDir);
            Dictionary<string, FileInfo> dstdic = CreateDic(dstdi);

            //删除SRC
            List<string> dstdelete = new List<string>();
            foreach(var kv in dstdic)
                if (!srcdic.ContainsKey(kv.Key))
                {
                    kv.Value.Delete();
                    dstdelete.Add(kv.Key);
                }
            foreach (var key in dstdelete)
                dstdic.Remove(key);

            //下载SRC
            List<string> download = new List<string>();
            foreach(var kv in srcdic)
                if (!dstdic.ContainsKey(kv.Key))
                {
                    download.Add(kv.Key);
                }
                else
                {
                    if (kv.Value.LastWriteTime != dstdic[kv.Key].LastWriteTime)
                    {//更新
                        download.Add(kv.Key);
                        dstdic[kv.Key].Delete();
                    }
                }
            //正式下载
            foreach (var key in download)
            {
                string srcpath = srcdic[key].FullName;
                string dstpath = srcpath.Replace(srcDir, destDir);
                string dstdir = dstpath.Replace( srcdic[key].Name,"");
                if(!Directory.Exists(dstdir))
                    Directory.CreateDirectory(dstdir);
                File.Copy(srcpath, dstpath);
            }
        }

        public static Dictionary<string, FileInfo> CreateDic(DirectoryInfo srcdi)
        {
            var files = srcdi.GetFiles("*.*", SearchOption.AllDirectories);
            return files.ToDictionary(r => r.FullName.Replace(srcdi.FullName, ""));
        }
        public void AsyncDir(string srcDir, string destDir)
        {
            
            if (!Directory.Exists(destDir))
            {
                Directory.CreateDirectory(destDir);
            }
            DirectoryInfo srcdi = new DirectoryInfo(srcDir);
            var files = srcdi.GetFiles();
            foreach (var fileInfo in files)
            {
                DateTime srcmodifytime = fileInfo.LastWriteTime;
                string dstfilepath = Path.Combine(destDir, fileInfo.Name);
                if (File.Exists(dstfilepath))
                {
                    FileInfo fi = new FileInfo(dstfilepath);
                    DateTime dstmodifytime = fi.LastWriteTime;
                    if (srcmodifytime == dstmodifytime)
                        continue;
                }
                File.Copy(Path.Combine(srcDir, fileInfo.Name), Path.Combine(destDir, fileInfo.Name), true);

                //var lowerFullName = fileInfo.FullName.ToLower();
                //if (_dcLastWriteTime.ContainsKey(lowerFullName))
                //{
                //    //文件的写入时间未改变时不处理
                //    if (fileInfo.LastWriteTime <= _dcLastWriteTime[lowerFullName])
                //        continue;
                //}
                //_dcLastWriteTime[lowerFullName] = fileInfo.LastWriteTime;
            }

            foreach (DirectoryInfo di in srcdi.GetDirectories())
            {
                AsyncDir(Path.Combine(srcDir, di.Name), Path.Combine(destDir, di.Name));
            }
        }

        public static bool connectState(string path)
        {
            return connectState(path, "", "");
        }
        public static bool connectState(string path, string userName, string passWord)
        {
            bool Flag = false;
            Process proc = new Process();
            try
            {
                proc.StartInfo.FileName = "cmd.exe";
                proc.StartInfo.UseShellExecute = false;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.Start();
                string dosLine = "net use " + path + " " + passWord + " /user:" + userName;
                if (userName == "")
                    dosLine = "net use " + path;
                proc.StandardInput.WriteLine(dosLine);
                proc.StandardInput.WriteLine("exit");
                while (!proc.HasExited)
                {
                    proc.WaitForExit(1000);
                }
                string errormsg = proc.StandardError.ReadToEnd();
                proc.StandardError.Close();
                if (string.IsNullOrEmpty(errormsg))
                {
                    Flag = true;
                }
                else
                {
                    throw new Exception(errormsg);
                }
            }
            catch (Exception ex)
            {
                //throw ex;
                MessageBox.Show(ex.Message);
            }
            finally
            {
                proc.Close();
                proc.Dispose();
            }
            return Flag;
        }
        /// <summary>
        /// 向远程文件夹保存本地内容，或者从远程文件夹下载文件到本地
        /// </summary>
        /// <param name="src">要保存的文件的路径，如果保存文件到共享文件夹，这个路径就是本地文件路径如：@"D:\1.avi"</param>
        /// <param name="dst">保存文件的路径，不含名称及扩展名</param>
        /// <param name="fileName">保存文件的名称以及扩展名</param>
        public static void Transport(string src, string dst, string fileName)
        {
            FileStream inFileStream = new FileStream(src, FileMode.Open);
            if (!Directory.Exists(dst))
            {
                Directory.CreateDirectory(dst);
            }
            dst = dst + fileName;
            FileStream outFileStream = new FileStream(dst, FileMode.OpenOrCreate);
            byte[] buf = new byte[inFileStream.Length];
            int byteCount;
            while ((byteCount = inFileStream.Read(buf, 0, buf.Length)) > 0)
            {
                outFileStream.Write(buf, 0, byteCount);
            }
            inFileStream.Flush();
            inFileStream.Close();
            outFileStream.Flush();
            outFileStream.Close();
        }
    }
    public class LocalToNet : ShareLocalNet
    {
        protected readonly string _srcDir;
        protected readonly string _destDir;
        public LocalToNet(string netpath, string user, string pwd, string locpath)
            : base(netpath, user, pwd, locpath)
        {
            _srcDir = locpath;
            _destDir = netpath;
        }

        public void AsycDir()
        {
            if (!TestConnet())
            {
                MessageBox.Show("无法连接");
                return;
            }
            //AsyncDir(_srcDir, _destDir);
            AsyncDir2(_srcDir, _destDir);
            MessageBox.Show("同步完成");
        }
    }
    public class NetToLocal : ShareLocalNet
    {
        protected readonly string _srcDir;
        protected readonly string _destDir;
        protected NetLocalPath _NetLocalPath;
        public NetToLocal(string netpath, string user, string pwd, string locpath,NetLocalPath netlocalpath=null)
            : base(netpath, user, pwd, locpath)
        {
            _srcDir = netpath;
            _destDir = locpath;
            this._NetLocalPath = netlocalpath;
        }

        public bool AsycDir()
        {
            if (!TestConnet())
            {
                MessageBox.Show("无法连接");
                return false;
            }
            //AsyncDir(_srcDir, _destDir);
            AsyncDir2(_srcDir, _destDir);
            if (_NetLocalPath != null)
            {
                AsyncDir2(_NetLocalPath.NetPath, _NetLocalPath.LocalPath);
            }
            return true;
        }
        public string GetNetResource(string NetPath)
        {
            if (!TestConnet())
            {
               return  "无法连接" ;
            }

            DirectoryInfo srcdi = new DirectoryInfo(NetPath);
            Dictionary<string, FileInfo> srcdic = CreateDic(srcdi);
            StringBuilder sb = new StringBuilder();
            foreach (KeyValuePair<string, FileInfo> kv in srcdic)
            {
                sb.AppendLine( "<a href=\""+kv.Value.FullName +"\">" + kv.Value + "</a><br>");
            }
            return sb.ToString();
        }
    }
}
